package com.atguigu.tingshu.common.config.thread;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @author xiaoxu
 * @description:
 * @date 2024/08/26 09:53
 **/
@Configuration
//@SuppressWarnings("all")
public class ThreadPoolConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {

        //1.获取逻辑处理核数
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        availableProcessors = availableProcessors * 2;
        ThreadPoolExecutor threadPoolExecutor =   new ThreadPoolExecutor(
                //核心线程数
                availableProcessors,
                //最大线程数
                availableProcessors,
                0,
                TimeUnit.SECONDS,
                // 阻塞队列
                new ArrayBlockingQueue<>(200),
                //使用默认的线程工厂
                Executors.defaultThreadFactory(),
                (r, j) -> {
                    //触发 自定义拒绝策略, 要求任务必须执行:
                    try {
                       Thread.sleep(2000);
                    } catch (InterruptedException e) {
                      throw new RuntimeException(e);
                    }
                    //将被拒绝的任务将再次 回到线程池进行执行
                    j.submit(r);
                }
        );
        //一开始就开启 核心线程 不等到任务提交过来才开始核心任务
        threadPoolExecutor.prestartAllCoreThreads();
        return  threadPoolExecutor;
    }
}
